package com.doodle.common.utils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class PostParameter implements Comparable<PostParameter> {

	private String mName = null;
	private String mValue = null;
	private String mEncodedValue = null;

	public PostParameter(String name, String value) {
		initValue(name, value, false);
	}

	public PostParameter(String name, double value) {
		initValue(name, String.valueOf(value), false);
	}
	
	public PostParameter(String name, long value) {
		initValue(name, String.valueOf(value), false);
	}

	public PostParameter(String name, int value) {
		initValue(name, String.valueOf(value), false);
	}
	
	public PostParameter(String name, String value, boolean encode) {
		initValue(name, value, encode);
	}

	public PostParameter(String name, double value, boolean encode) {
		initValue(name, String.valueOf(value), encode);
	}

	public PostParameter(String name, int value, boolean encode) {
		initValue(name, String.valueOf(value), encode);
	}
	
	private void initValue(String name, String value, boolean encode) {
		mName = name;
		mValue = value;
		if (encode) {
			mEncodedValue = percentEncode(value);
		}
	}

	public String getName() {
		return mName;
	}

	public String getValue() {
		return mValue;
	}
	
	public String getParamValue() {
		return Utils.isEmpty(mEncodedValue) ? mValue : mEncodedValue;
	}

	public int hashCode() {
		int result = mName.hashCode();
		result = 31 * result + mValue.hashCode();
		return result;
	}

	public boolean equals(Object obj) {
		if (null == obj) {
			return false;
		}
		if (this == obj) {
			return true;
		}
		if (obj instanceof PostParameter) {
			PostParameter that = (PostParameter) obj;
			return mName.equals(that.mName) && mValue.equals(that.mValue);
		}
		return false;
	}

	@Override
	public int compareTo(PostParameter another) {
		int compared = mName.compareTo(another.mName);
		if (compared == 0) {
			compared = mValue.compareTo(another.mValue);
		}
		return compared;
	}
	
	private static String percentEncode(String value) {
		if (value == null) {
			return "";
		}
		try {
			return URLEncoder.encode(value, "UTF-8").replace("+", "%20")
					.replace("*", "%2A").replace("%7E", "~");
		} catch (UnsupportedEncodingException ex) {
		}
		return value;
	}
}
